// 需要导入vue-router router有三种模式，history、hash、abstract 使用history模式需要导入createWebHistory
import { createRouter, createWebHistory } from "vue-router";

import Home from "./views/Home.vue";
// import Login from "./views/Login.vue";
// import ColumnDetail from "./views/ColumnDetail.vue";
// import CreatePost from "./views/CreatePost.vue";
import store from "./store";
// import Signup from "./views/Signup.vue";
// import PostDetail from "./views/PostDetail.vue";
// import EditProfile from "./views/EditProfile.vue";
import axios from "axios";
const routerHistory = createWebHistory();
const router = createRouter({
  history: routerHistory, //vue3中的history配置 而不是vue2中的mode: 'history'
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
      meta: { redirectAlreadyLogin: true } //登录后，不需要再进来
    },

    {
      path: "/edit",
      name: "edit",
      component: () => import("@/views/EditProfile.vue"),
      meta: {
        requiredLogin: true // 需要登录之后才可访问
      }
    },
    {
      path: "/column/:id",
      name: "column",
      component: () => import("@/views/ColumnDetail.vue")
    },
    {
      path: "/create",
      name: "createPost",
      component: () => import("@/views/CreatePost.vue"),
      meta: {
        requiredLogin: true // 需要登录之后才可访问
      }
    },
    {
      path: "/signup",
      name: "signup",
      component: () => import("@/views/Signup.vue"),
      meta: { redirectAlreadyLogin: true } //登录后，不需要再进来
    },
    {
      path: "/posts/:id",
      name: "post",
      component: () => import("@/views/PostDetail.vue")
    }
  ]
});
// 前置路由守卫
// 存在的问题是 如果直接访问/create路由并刷新 会重新跳转到login页面 此时的store.state.user.isLogin是初始化为false的，还没发送异步请求就已经执行了路由守卫
/*router.beforeEach((to, from, next) => {
  if (!store.state.user.isLogin && to.meta.requiredLogin) {
    //访问需要权限的页面
    next({ name: "login" }); // 跳转到login登录页面
  } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
    next({ name: "home" });
  } else {
    next();
  }
});*/
router.beforeEach((to, from, next) => {
  const { user, token } = store.state;
  const { requiredLogin, redirectAlreadyLogin } = to.meta;
  if (!user.isLogin) {
    // 如果用户没有登录
    if (token) {
      // 检查是否有token->有的话就拿着这个令牌去向服务端要user的信息
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      store
        .dispatch("fetchCurrentUser")
        .then(() => {
          if (redirectAlreadyLogin) {
            next("/");
          } else {
            next();
          }
        })
        .catch(e => {
          // 如果失败 说明可能网络有问题或者是token已经过期 此时需要重新登录
          console.error(e);
          store.commit("logout");
          // localStorage.removeItem("token"); 只是这里清除了还不够 state中没有删除
          next("login");
        });
    } else {
      // 若没有token 说明该访问者从来没有登陆过，此时就看是不是需要权限的页面了
      if (requiredLogin) {
        next("login");
      } else {
        next();
      }
    }
  } else {
    // 如果已经登录 此时再访问/login /signup就会自动跳转到首页
    if (redirectAlreadyLogin) {
      next("/");
    } else {
      next();
    }
  }
});

export default router;
